package com.ruoyi.business.customer.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.business.base.JoBaseServiceImpl;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.customer.domain.JbOpportunity;
import com.ruoyi.business.customer.domain.vo.JbOpportunityExcle;
import com.ruoyi.business.customer.domain.vo.JbOpportunityInfoVo;
import com.ruoyi.business.customer.domain.vo.JbOpportunityListVo;
import com.ruoyi.business.customer.mapper.JbOpportunityMapper;
import com.ruoyi.business.customer.service.JbOpportunityService;
import com.ruoyi.business.goods.domain.JbCropVariety;
import com.ruoyi.business.goods.service.JbCropVarietyService;
import com.ruoyi.business.sundry.service.SysDataScopeFactoryService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.RoleEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysDictDataServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 商机Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Service
@Slf4j
public class JbOpportunityServiceImpl
        extends JoBaseServiceImpl<JbOpportunityMapper, JbOpportunity>
        implements JbOpportunityService
{
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private JbCropVarietyService jbCropVarietyService;
    @Autowired
    private SysDictDataServiceImpl sysDictDataService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysDataScopeFactoryService sysDataScopeFactoryService;


    @Override
    public IPage<JbOpportunityListVo> pageList(PageParam pageParam, JbOpportunity jbOpportunity)
    {
        LambdaQueryWrapper<JbOpportunity> select = Wrappers.lambdaQuery();
        select.like(StringUtils.isNotBlank(jbOpportunity.getPhoneNumber()), JbOpportunity::getPhoneNumber, jbOpportunity.getPhoneNumber())
                .eq(StringUtils.isNotBlank(jbOpportunity.getOpportunitySource()), JbOpportunity::getOpportunitySource, jbOpportunity.getOpportunitySource())
                .eq(ObjectUtils.isNotEmpty(jbOpportunity.getDistributionStatus()), JbOpportunity::getDistributionStatus, jbOpportunity.getDistributionStatus());
        // 去掉数据维度查询，可以部门要看到小组分给谁
        // 去现场要求转移后后就删除
        select.eq(ObjectUtils.isNotEmpty(jbOpportunity.getOpportunityDataType())
                , JbOpportunity::getOpportunityDataType, jbOpportunity.getOpportunityDataType());
        setRoleData(jbOpportunity,select);
        if (StringUtils.isNotBlank(pageParam.getSortKey()) && ObjectUtils.isNotEmpty(pageParam.getSortKeyValues()))
        {
            select.last(String.format(" order by %s %s ", pageParam.getSortKey(), pageParam.getSortKeyValues()));
        } else
        {
            select.orderByDesc(JbOpportunity::getId);
        }
        IPage<JbOpportunity> page = this.page(pageParam.b(), select);
        List<JbOpportunity> list = page.getRecords();
        List<JbOpportunityListVo> listVo = Lists.newArrayList();
        if (ObjectUtils.isNotEmpty(list))
        {
            List<Long> deptIds = Lists.newArrayList();
            List<Long> userIds = Lists.newArrayList();
            for (JbOpportunity opportunity : list)
            {
                if (ObjectUtils.isNotEmpty(opportunity.getDepartmentId())) deptIds.add(opportunity.getDepartmentId());
                if (ObjectUtils.isNotEmpty(opportunity.getTeamId())) deptIds.add(opportunity.getTeamId());
                if (ObjectUtils.isNotEmpty(opportunity.getBusinessManagerId()))
                    userIds.add(opportunity.getBusinessManagerId());
            }
            Map<Long, String> collectDept = new HashMap<>();
            Map<Long, SysUser> collectUser = new HashMap<>();
            if (ObjectUtils.isNotEmpty(deptIds))
            {
                List<SysDept> sysDeptList = sysDeptService.list(new LambdaQueryWrapper<SysDept>().in(SysDept::getDeptId, deptIds)
                        .select(SysDept::getDeptId, SysDept::getDeptName));
                collectDept = sysDeptList.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName));
            }
            if (ObjectUtils.isNotEmpty(userIds))
            {
                List<SysUser> sysUserList = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getUserId, userIds)
                        .select(SysUser::getUserId, SysUser::getUserName));
                collectUser = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
            }
            for (JbOpportunity opportunity : list)
            {
                JbOpportunityListVo unityVo = new JbOpportunityListVo();
                unityVo.setDepartName(ObjectUtils.isNotEmpty(opportunity.getDepartmentId()) ? collectDept.get(opportunity.getDepartmentId()) : Strings.EMPTY);
                unityVo.setTeamName(ObjectUtils.isNotEmpty(opportunity.getTeamId()) ? collectDept.get(opportunity.getTeamId()) : Strings.EMPTY);
                SysUser sysUser = collectUser.get(opportunity.getBusinessManagerId());
                if (ObjectUtils.isNotEmpty(sysUser))
                {
                    unityVo.setBusinessManagerName(sysUser.getUserName());
                    unityVo.setAvatar(sysUser.getAvatar());
                }
                BeanUtils.copyProperties(opportunity, unityVo, JbOpportunityListVo.class);
                listVo.add(unityVo);
            }

        }
        IPage<JbOpportunityListVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(listVo);

        return pageVo;
    }
    private void setRoleData(JbOpportunity jbOpportunity,LambdaQueryWrapper<JbOpportunity> select)
    {
        //角色数据权限
        List<Long> roleData=null;
        if (SecurityUtils.hasUserRole(RoleEnum.CUSTOMER_SERVICE.getCode()))
        {
            // 客户角色按创建人过滤
            roleData=sysDataScopeFactoryService.fnListDataScope(Constants.PUBLIC_NUMBER_0.toString());
            select.in(ObjectUtils.isNotEmpty(roleData),
                    JbOpportunity::getCreateBy, roleData);
        } else
        {
            // 商机数据类型0=公共1=部门2=小组3=个人
            if (jbOpportunity.getOpportunityDataType().equals(Constants.PUBLIC_NUMBER_1))
            {
                //角色是组长访问的部门的数据，获取他本部门的数据

                if (SecurityUtils.hasUserRole(RoleEnum.GROUPLEADER.getCode()))
                {
                    //如果是组长角色，获取上级部门的id，获取他本部门的数据
                    String roleDataParentId =SecurityUtils.getLoginUser().getUser().getDept().getParentId().toString();
                    select.eq(StrUtil.isNotBlank(roleDataParentId),
                            JbOpportunity::getDepartmentId, roleDataParentId);
                }else
                {
                    roleData=sysDataScopeFactoryService.fnListDataScope(Constants.PUBLIC_NUMBER_1.toString());;
                }
                select.in(ObjectUtils.isNotEmpty(roleData),
                        JbOpportunity::getDepartmentId, roleData);
            } else if (jbOpportunity.getOpportunityDataType().equals(Constants.PUBLIC_NUMBER_2))
            {
                roleData=sysDataScopeFactoryService.fnListDataScope(Constants.PUBLIC_NUMBER_1.toString());;
                select.in(ObjectUtils.isNotEmpty(roleData),
                        JbOpportunity::getTeamId, roleData);
            } else if (jbOpportunity.getOpportunityDataType().equals(Constants.PUBLIC_NUMBER_3)
                    || jbOpportunity.getOpportunityDataType().equals(Constants.PUBLIC_NUMBER_0))
            {
                roleData=sysDataScopeFactoryService.fnListDataScope(Constants.PUBLIC_NUMBER_0.toString());;
                select.in(ObjectUtils.isNotEmpty(roleData),
                        JbOpportunity::getBusinessManagerId,roleData);
            }
        }

    }
    @Override
    public JbOpportunityInfoVo getInfo(Long id)
    {
        JbOpportunity opportunity = this.getById(id);
        JbOpportunityInfoVo infoVo = new JbOpportunityInfoVo();
        BeanUtils.copyProperties(opportunity, infoVo);
        if (ObjectUtils.isNotEmpty(opportunity.getDepartmentId()))
        {
            SysDept one = sysDeptService.getOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptId, opportunity.getDepartmentId())
                    .select(SysDept::getDeptName));
            infoVo.setDepartName(Optional.ofNullable(one).map(SysDept::getDeptName).orElse(Strings.EMPTY));
        }
        if (ObjectUtils.isNotEmpty(opportunity.getTeamId()))
        {
            SysDept one = sysDeptService.getOne(new LambdaQueryWrapper<SysDept>().eq(SysDept::getDeptId, opportunity.getTeamId())
                    .select(SysDept::getDeptName));
            infoVo.setTeamName(Optional.ofNullable(one).map(SysDept::getDeptName).orElse(Strings.EMPTY));
        }
        if (ObjectUtils.isNotEmpty(opportunity.getBusinessManagerId()))
        {
            SysUser one = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, opportunity.getBusinessManagerId())
                    .select(SysUser::getUserName));
            infoVo.setBusinessManagerName(Optional.ofNullable(one).map(SysUser::getUserName).orElse(Strings.EMPTY));
        }
        if (StringUtils.isNotEmpty(opportunity.getCropIds()))
        {
            List<Long> cropLists = Arrays.stream(opportunity.getCropIds().split(",")).map(Long::valueOf).collect(Collectors.toList());

            List<JbCropVariety> jbCropGrowthPeriods = jbCropVarietyService.listByIds(cropLists);
            String collect = jbCropGrowthPeriods.stream().map(JbCropVariety::getCropName).collect(Collectors.joining(","));
            infoVo.setCropNames(collect);
        }
        return infoVo;
    }

    @Override
    public Boolean importData(List<JbOpportunityExcle> jbCustomerList)
    {
        // 获取字段数据，把汉字转成编码
        List<SysDictData> list = sysDictDataService.list(Wrappers.lambdaQuery(SysDictData.class)
                .in(SysDictData::getDictType, new String[]{"bus_source", "bus_channel", "honorific"})
                .select(SysDictData::getDictCode, SysDictData::getDictValue, SysDictData::getDictLabel));
        Map<String, List<SysDictData>> collect = list.stream().collect(Collectors.groupingBy(SysDictData::getDictLabel));
        List<SysDept> deptList = sysDeptService.list(Wrappers.lambdaQuery(SysDept.class)
                .eq(SysDept::getDelFlag, Constants.PUBLIC_NUMBER_0)
                .eq(SysDept::getStatus, Constants.PUBLIC_NUMBER_0)
                .eq(SysDept::getLevel, Constants.PUBLIC_NUMBER_2)
                .select(SysDept::getDeptId, SysDept::getDeptName)
        );
        Map<String, List<SysDept>> mapDeptList = deptList.stream().collect(Collectors.groupingBy(SysDept::getDeptName));
        jbCustomerList.forEach(a ->
        {
            a.setOpportunitySource(getMap(a.getOpportunitySource(), collect));
            a.setOpportunityChannel(getMap(a.getOpportunityChannel(), collect));
            a.setCustomerTitle(getMap(a.getCustomerTitle(), collect));
            List<SysDept> sysDeptList = mapDeptList.get(a.getDeptName());
            if (ObjectUtils.isNotEmpty(sysDeptList) && ObjectUtils.isNotEmpty(sysDeptList.get(0)))
            {
                a.setDeptId(sysDeptList.get(0).getDeptId());
            }
        });
        return this.saveBatch(
                BeanUtil.copyToList(jbCustomerList, JbOpportunity.class));
    }

    /**
     * 字典名称转code
     *
     * @param key
     * @param collect
     * @return
     */
    private String getMap(String key, Map<String, List<SysDictData>> collect)
    {
        String code = key;
        if (StringUtils.isBlank(key))
        {
            return code;
        }
        List<SysDictData> sysDictData = collect.get(key);
        if (ObjectUtils.isNotEmpty(sysDictData) && ObjectUtils.isNotEmpty(sysDictData.get(0))
                && StringUtils.isNotBlank(sysDictData.get(0).getDictValue()))
        {
            code = sysDictData.get(0).getDictValue();
        }
        return code;
    }
}
